package com.ydc.ln.tutorial.clasler;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.ArrayList;

import javax.imageio.ImageIO;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;

public class ImageClasler {
	private static String PIC_GESHI = "jpg";
	
	private static String DIR = "E:\\TEMP\\";
	// http://www.sina.com.cn/ http://www.baidu.com 	http://www.duote.com/	http://findicons.com/search/mail
	private static String URL = "http://www.88web.org/css-templates.htm";
	private static String PIC = "." + PIC_GESHI;
	private static String SPLIT_PIC = "\\." + PIC_GESHI;
	private static String FILENAME = "jpg";

	public static void main(String[] args) throws ClientProtocolException, IOException {
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(URL);
		
		httpGet.setHeader("Accept-Charset", "UTF-8;q=0.7,*;q=0.7"); 
		
		HttpResponse response = httpClient.execute(httpGet);
		HttpEntity entity = response.getEntity();
		System.out.println();
		StringBuilder builder = new StringBuilder();
		if (entity != null) {
			InputStream inputStream = entity.getContent();
			if(inputStream != null) {
				if(entity.getContentLength() <= Integer.MAX_VALUE) {
					int i = (int) entity.getContentLength();
					if(i < 0) {
						i = 4096;
					}
					String charset = EntityUtils.getContentCharSet(entity);
					if(charset == null) {
						charset = "UTF-8";
					}
					Reader reader = new InputStreamReader(inputStream, charset);
					CharArrayBuffer buffer = new CharArrayBuffer(i);                         
				}
			}
			int l;
			byte[] temp = new byte[1];
			while ((l = inputStream.read(temp)) != -1) {
				//System.out.print("[" + temp + "]");
				String str = new String(temp, "UTF-8");
				System.out.print(str);                                        
				builder.append(str);
			}

		}
		
		// saveContent(builder.toString());
		// ArrayList<String> imgs = analyseImgs(builder.toString());
		// savetodisk(imgs, makedir(ImageClasler.URL));
	}

	/**
	 * 保存网页内容
	 * @param content
	 */
	public static void saveContent(String content) {
		File file = new File("f:\\content.txt");
		boolean flag = true;
		if (!file.exists()) {
			try {
				flag = file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (flag) {
			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(file);
				fos.write(content.getBytes());
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException ie) {
				ie.printStackTrace();
			} finally {
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	/**
	 * 根据URL创建目录
	 * 
	 * @param url
	 */
	private static String makedir(String url) {
		String dirname = url.substring("http://".length(), url.lastIndexOf("."));
		File file = new File(ImageClasler.DIR + dirname);
		if (!file.exists()) {
			file.mkdirs();
		}
		return file.getPath();
	}

	/**
	 * 存储图片到硬盘
	 * 
	 * @param imgs
	 * @param diskuri
	 */
	private static void savetodisk(ArrayList<String> imgs, String diskuri) {
		for (String tt : imgs) {
			System.out.println("图片地址: " + tt);
			ImageClasler.writeImageLocal(diskuri + tt.substring(tt.lastIndexOf("/"), tt.lastIndexOf(PIC)) + PIC, ImageClasler.loadImageUrl(tt));
		}
		System.out.println("---------------------------over");

	}

	/**
	 * 根据获取到的HTML页面分析图片
	 * 
	 * @param string
	 * @return
	 */
	private static ArrayList<String> analyseImgs(String string) {
		// System.out.println(string);
		ArrayList<String> list = new ArrayList<String>();
		String[] temp = string.split(SPLIT_PIC);
		for (int i = 0; i < temp.length - 1; i++) {
			String a = temp[i];
			// System.out.println(a);
			// System.out.println("----------------------------------------------------------------------");
			// String str = a.substring(a.lastIndexOf("http://")) + PIC;
			// System.out.println(str);
			list.add(a.substring(a.lastIndexOf("http://")) + PIC);
		}
		return list;
	}

	/**
	 * 通过URL地址获取图片
	 * 
	 * @param imgName
	 * @return
	 */
	public static BufferedImage loadImageUrl(String imgName) {
		try {
			URL url = new URL(imgName);
			return ImageIO.read(url);
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
		return null;
	}

	/**
	 * 生成新图片到本地
	 */
	public static void writeImageLocal(String newImage, BufferedImage img) {
		if (newImage != null && img != null) {
			try {
				File outputfile = new File(newImage);
				ImageIO.write(img, FILENAME, outputfile);
				System.out.println("one jpg saved to " + outputfile.getAbsolutePath());
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
		}
	}
}
